class SolutionBuildTreeByPostAndIno {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public int postIndex = 0;

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = postorder.length - 1;
        return buildTreeChild(postorder, inorder, 0, inorder.length - 1);
    }

    public TreeNode buildTreeChild(int[] postorder, int[] inorder, int inbegin, int inend) {
        if (inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode(postorder[postIndex]);

        int rootIndex = findRootIndex(inorder, inbegin, inend, postorder[postIndex]);
        postIndex--;

        root.right = buildTreeChild(postorder, inorder, rootIndex + 1, inend);

        root.left = buildTreeChild(postorder, inorder, inbegin, rootIndex - 1);

        return root;
    }

    private int findRootIndex(int[] inorder, int inbegin, int inend, int key) {
        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
}